<template>
  <view class="login-container">
    <!-- 自定义状态栏 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    <!-- 欢迎标题 -->
    <view class="welcome-section">
      <text class="welcome-title">欢迎来到禧易宝商家端</text>
    </view>
    <view class="main">
      <!-- 主要内容区域 -->
      <view class="content">
        <!-- 选项卡 -->
        <uni-segmented-control
          :current="currentTabIndex"
          :values="tabOptions"
          style-type="text"
          active-color="#ff8c00"
          @clickItem="onTabChange"
          class="tab"
        />
        <!-- 表单内容 -->
        <uni-forms
          ref="loginForm"
          :model="formData"
          :rules="formRules"
          class="form-content mt-20rpx"
        >
          <!-- 账号输入框 -->
          <uni-forms-item name="me" class="input-group">
            <MyInput
              v-model="formData.me"
              placeholder="请输入您的账号"
              :clearable="true"
              iconType="person"
              focusIconColor="#ff9714"
            />
          </uni-forms-item>

          <!-- 密码输入框 -->
          <uni-forms-item
            name="password"
            class="input-group"
            v-if="currentTab === 'password'"
          >
            <MyInput
              v-model="formData.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入您账号密码"
              iconType="locked"
              :showPasswordIcon="true"
              focusIconColor="#ff9714"
              @iconClick="togglePassword"
            />
          </uni-forms-item>

          <!-- 验证码输入框 -->
          <uni-forms-item
            name="code"
            class="input-group"
            v-if="currentTab === 'code'"
          >
            <view class="code-input-wrapper">
              <MyInput
                v-model="formData.code"
                class="code-input"
                placeholder="请输入验证码"
                type="number"
                iconType="phone"
                focusIconColor="#ff9714"
              />
              <uni-button
                class="send-code-btn line-height-60rpx bg-#ff9714! color-#fff text-center"
                type="primary"
                size="mini"
                @click="sendCode"
              >
                {{ codeText }}
              </uni-button>
            </view>
          </uni-forms-item>

          <!-- 协议勾选 -->
          <uni-forms-item name="agreed" class="agreement-section">
            <uni-data-checkbox
              v-model="agreementValue"
              :localdata="agreementOptions"
              :multiple="false"
              @change="onAgreementChange"
            />
          </uni-forms-item>

          <!-- 登录按钮 -->
          <uni-forms-item class="login-btn-wrapper">
            <uni-button
              class="login-btn w100% text-center color-#fff bg-#ff9714 line-height-88rpx h88rpx"
              @click="handleLogin"
            >
              登录
            </uni-button>
          </uni-forms-item>
        </uni-forms>

        <!-- 说明文字 -->
        <view class="description">
          <text class="desc-text">
            禧易宝商家端是为禧易宝员工、客户、供应商提供的内部协同工具，使用者必须是已有账号的内部员工。
          </text>
          <text class="desc-warning">外部人员不开放使用</text>
        </view>
      </view>
      <!-- 底部操作 -->
      <view class="bottom-actions">
        <view class="action-item" @click="navigateToRegister">
          <view class="action-icon">
            <uni-icons type="person-filled" size="20" color="#ff8c00" />
          </view>
          <text class="action-text">注册账号</text>
        </view>
        <!-- <view class="action-item" @click="navigateToGuide"> -->
        <!--   <view class="action-icon"> -->
        <!--     <uni-icons type="person" size="20" color="#ff8c00" /> -->
        <!--   </view> -->
        <!--   <text class="action-text">导购账号登录</text> -->
        <!-- </view> -->
        <view class="action-item" @click="navigateToPartner">
          <view class="action-icon">
            <uni-icons type="chat" size="20" color="#ff8c00" />
          </view>
          <text class="action-text">新商家合作</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import MyInput from "@/components/common/MyInput/MyInput.vue";
import { encryptPassword } from "@/utils/crypto";
import { useRequest } from "ahooks-vue";
import {
  loginByAccount,
  loginByCode,
  sendCode as sendCodeApi,
} from "@/api/user";
import { useUserStore } from "@/store/modules/user";

// 使用 Pinia store
const userStore = useUserStore();

// 响应式数据
const statusBarHeight = ref(44); // 状态栏高度
const currentTab = ref("password"); // 当前选项卡
const currentTabIndex = ref(0); // 当前选项卡索引
const showPassword = ref(false); // 是否显示密码
const codeCountdown = ref(0); // 验证码倒计时
// const loginLoading = ref(false); // 登录加载状态
const loginForm = ref(); // 表单引用

// 表单数据
const formData = ref({
  me: "",
  password: "",
  code: "",
  type: 3,
});

// 选项卡配置
const tabOptions = ref(["密码登录", "验证码登录"]);

// 协议勾选配置
const agreementValue = ref([]);
const agreementOptions = ref([
  {
    text: "我已阅读并同意《隐私政策》",
    value: "agreed",
  },
]);

// 表单验证规则
const formRules = ref({
  me: {
    rules: [
      {
        required: true,
        errorMessage: "请输入账号",
      },
    ],
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: "请输入密码",
      },
    ],
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: "请输入验证码",
      },
    ],
  },
});

// 计算属性
const canLogin = computed(() => {
  const hasAccount = formData.value.me.length > 0;
  const hasPassword =
    currentTab.value === "password" ? formData.value.password.length > 0 : true;
  const hasCode =
    currentTab.value === "code" ? formData.value.code.length > 0 : true;
  const hasAgreed = agreementValue.value.includes("agreed");

  return hasAccount && (hasPassword || hasCode) && hasAgreed;
});

const codeText = computed(() => {
  return codeCountdown.value > 0 ? `${codeCountdown.value}s` : "发送验证码";
});

// 方法
const onTabChange = (e) => {
  currentTabIndex.value = e.currentIndex;
  const tab = e.currentIndex === 0 ? "password" : "code";
  currentTab.value = tab;

  // 清空其他类型的输入
  if (tab === "password") {
    formData.value.code = "";
  } else {
    formData.value.password = "";
  }
};

const switchTab = (tab) => {
  currentTab.value = tab;
  currentTabIndex.value = tab === "password" ? 0 : 1;

  // 清空其他类型的输入
  if (tab === "password") {
    formData.value.code = "";
  } else {
    formData.value.password = "";
  }
};

const togglePassword = () => {
  showPassword.value = !showPassword.value;
};

const onAgreementChange = (e) => {
  agreementValue.value = e.detail.value;
  formData.value.agreed = e.detail.value.includes("agreed");
};

const sendCode = () => {
  if (codeCountdown.value > 0) return;
  if (!formData.value.me) {
    uni.showToast({
      title: "请先输入账号",
      icon: "none",
    });
    return;
  }

  // 调用发送验证码接口
  // 注意：发送验证码接口的参数是 ac（邮箱/手机号）
  sendCodeApi({
    ac: formData.value.me,
  })
    .then(() => {
      uni.showToast({
        title: "验证码已发送",
        icon: "none",
      });

      // 开始倒计时
      codeCountdown.value = 60;
      const timer = setInterval(() => {
        codeCountdown.value--;
        if (codeCountdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    })
    .catch((error) => {
      uni.showToast({
        title: error.message || "发送失败，请重试",
        icon: "none",
      });
    });
};

// 账号密码登录请求
const { run: loginByAccountRun, loading: loginByAccountLoading } = useRequest(
  (data) => loginByAccount(data),
  {
    manual: true,
    onSuccess: (result) => {
      console.log("登录成功，返回数据：", result);

      // 使用 Pinia store 保存用户信息和 token
      if (result.data) {
        // 保存用户信息到 Pinia store（会自动持久化）
        if (result.data.loginSubscribersVO) {
          userStore.setUserInfo(result.data.loginSubscribersVO);
          uni.setStorageSync("userInfo", result.data.loginSubscribersVO);
        }
        // 保存 token 到 Pinia store（会自动持久化）
        if (result.data.token) {
          userStore.setToken(result.data.token);
          uni.setStorageSync("token", result.data.token);
        }
        // 保存 AES 加密所需的 token1、token2、token3（这些仍然使用 uni.setStorageSync）
        if (result.data.token1) {
          uni.setStorageSync("token1", result.data.token1);
        }
        if (result.data.token2) {
          uni.setStorageSync("token2", result.data.token2);
        }
        if (result.data.token3) {
          uni.setStorageSync("token3", result.data.token3);
        }
      }

      uni.showToast({
        title: "登录成功",
        icon: "none",
      });

      // 登录成功后跳转到首页
      setTimeout(() => {
        uni.navigateTo({
          url: "/pages/login/chooseStore/chooseStore",
        });
      }, 1500);
    },
    onError: (error) => {
      console.error("登录失败：", error);
      uni.showToast({
        title: error.message || "登录失败，请重试",
        icon: "none",
      });
    },
  }
);

// 验证码登录请求
const { run: loginByCodeRun, loading: loginByCodeLoading } = useRequest(
  (data) => loginByCode(data),
  {
    manual: true,
    onSuccess: (result) => {
      console.log("验证码登录成功，返回数据：", result);

      // 使用 Pinia store 保存用户信息和 token
      if (result.data) {
        // 保存用户信息到 Pinia store（会自动持久化）
        if (result.data.loginSubscribersVO) {
          userStore.setUserInfo(result.data.loginSubscribersVO);
        }
        // 保存 token 到 Pinia store（会自动持久化）
        if (result.data.token) {
          userStore.setToken(result.data.token);
        }
      }

      uni.showToast({
        title: "登录成功",
        icon: "none",
      });

      // 登录成功后跳转到首页
      setTimeout(() => {
        uni.navigateTo({
          url: "/pages/login/chooseStore/chooseStore",
        });
      }, 1500);
    },
    onError: (error) => {
      console.error("验证码登录失败：", error);
      uni.showToast({
        title: error.message || "登录失败，请重试",
        icon: "none",
      });
    },
  }
);

// 合并 loading 状态
const loginLoading = computed(() => {
  return loginByAccountLoading.value || loginByCodeLoading.value;
});

// 登录处理函数
const handleLogin = async () => {
  try {
    // 表单验证
    await loginForm.value.validate();

    if (!canLogin.value) return;

    // 根据登录方式调用不同的接口
    if (currentTab.value === "password") {
      // 密码登录
      const encryptedPassword = encryptPassword(formData.value.password);
      if (!encryptedPassword) {
        uni.showToast({
          title: "密码加密失败，请重试",
          icon: "none",
        });
        return;
      }

      const loginData = {
        me: formData.value.me,
        password: encryptedPassword,
        type: formData.value.type,
      };

      console.log("准备密码登录，数据：", {
        ...loginData,
        password: "***",
      });

      await loginByAccountRun(loginData);
    } else {
      // 验证码登录
      const loginData = {
        me: formData.value.me,
        code: parseInt(formData.value.code), // 转换为整数
        type: formData.value.type,
      };

      console.log("准备验证码登录，数据：", loginData);

      await loginByCodeRun(loginData);
    }
  } catch (error) {
    console.error("表单验证失败：", error);
    if (error.errorFields) {
      // 表单验证错误
      uni.showToast({
        title: "请检查输入信息",
        icon: "none",
      });
    }
  }
};

const navigateToRegister = () => {
  uni.navigateTo({
    url: "/pages/login/register",
  });
};

const navigateToGuide = () => {
  uni.showToast({
    title: "导购登录功能开发中",
    icon: "none",
  });
};

const navigateToPartner = () => {
  uni.navigateTo({
    url: "/pages/login/partner/partner",
  });
};

// 生命周期
onMounted(() => {
  // 获取系统信息
  uni.getSystemInfo({
    success: (res) => {
      statusBarHeight.value = res.statusBarHeight || 44;
    },
  });
});
</script>

<style scoped lang="scss">
.main {
  flex: 1;
  background-color: #fff;
  padding: 40rpx;
  border-radius: 40rpx 40rpx 0 0;
}
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffb347 0%, #ff8c00 100%);
  display: flex;
  flex-direction: column;
}

.status-bar {
  width: 100%;
  background: transparent;
}

.content {
  flex: 1;
}

.welcome-section {
  text-align: center;
  margin-bottom: 80rpx;

  .welcome-title {
    display: block;
    font-size: 48rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }

  .welcome-subtitle {
    display: block;
    font-size: 28rpx;
    color: #666;
    opacity: 0.8;
  }
}

.form-content {
  // uni-forms 样式
  :deep(.uni-forms) {
    .uni-forms-item__label {
      display: none !important; // 隐藏标签
    }

    .uni-forms-item__content {
      padding: 0 !important;
    }

    .uni-forms-item__error {
      margin-top: 10rpx !important;
      margin-left: 30rpx !important;
      font-size: 24rpx !important;
      color: #ff4444 !important;
    }
  }

  .input-group {
    margin-bottom: 40rpx;

    // 验证码输入框布局
    .code-input-wrapper {
      display: flex;
      align-items: center;
      gap: 20rpx;

      .code-input {
        flex: 1;
      }

      .send-code-btn {
        height: 60rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        white-space: nowrap;
        min-width: 140rpx;

        &.uni-button-disabled {
          background: #ddd !important;
          color: #999 !important;
        }
      }
    }
  }
}

.agreement-section {
  margin: 40rpx 0;

  :deep(.is-checked) {
    .radio__inner {
      border-color: #ffb347 !important;
      .radio__inner-icon {
        background-color: #ffb347 !important;
      }
    }
    .checklist-text {
      color: #ffb347 !important;
    }
  }
}

.login-btn-wrapper {
  margin: 60rpx 0 40rpx;

  .login-btn {
    width: 100%;
    height: 88rpx;
    border-radius: 50rpx;
    font-size: 32rpx;
    font-weight: 600;

    // uni-button 样式覆盖
    :deep(.uni-button) {
      background: #ff8c00 !important;
      color: #fff !important;
      border: none !important;
      border-radius: 50rpx !important;
      font-size: 32rpx !important;
      font-weight: 600 !important;

      &.uni-button-disabled {
        background: #ddd !important;
        color: #999 !important;
      }

      &.uni-button-loading {
        background: #ff8c00 !important;
        opacity: 0.8 !important;
      }
    }

    // 原生 button 样式（备用）
    &.disabled {
      background: #ddd;
      color: #999;
    }
  }
}

.description {
  text-align: center;
  line-height: 1.6;

  .desc-text {
    display: block;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
  }

  .desc-warning {
    display: block;
    font-size: 24rpx;
    color: #ff4444;
    font-weight: 600;
  }
}

.bottom-actions {
  display: flex;
  justify-content: space-around;

  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;

    .action-icon {
      width: 80rpx;
      height: 80rpx;
      background: #f8f9fa;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20rpx;

      // uni-icons 样式
      :deep(.uni-icons) {
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
      }
    }

    .action-text {
      font-size: 24rpx;
      color: #666;
    }
  }
}
:deep(.segmented-control__item--text) {
  border-color: #ff9714 !important;
}
</style>
